﻿using System;
using System.Collections.Generic;
using System.Linq;
using Company.Merchandising.BusinessLayer.DataEntities;
using Company.Merchandising.BusinessLayer.DataTransferObjects;
using Company.Merchandising.DataAccessLayer.DataAccessCommon;
using Company.Merchandising.ServiceLayer.EntityManagement.Constants;

namespace Company.Merchandising.ServiceLayer.EntityManagement
{
	public class RoleManager : BaseManager
	{
		public RoleManager(MerchModelEntities modelEntities) : base(modelEntities) { }

		public void AddRole(DTORole roleToAdd, IList<DTOFaculty> chosenFaculties)
		{
			DACRole dacRole = new DACRole(_modelEntities);
			if (dacRole.GetRolesByName(roleToAdd.Name).Count() > 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.RoleAlreadyExist, roleToAdd.Name));
			}

			if (chosenFaculties.Count == 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.RoleMustHaveAtLeastOneFunctionality, roleToAdd.Name));
			}

			var newRole = new Role();
			newRole.Name = roleToAdd.Name;
			newRole.Description = roleToAdd.Description;

			DACFaculty dacFaculty = new DACFaculty(_modelEntities);
			foreach (var faculty in chosenFaculties)
			{
				newRole.Faculties.Add(dacFaculty.GetFacultyById(faculty.Id));
			}

			_modelEntities.AddObject(newRole.GetType().Name, newRole);
			_modelEntities.SaveChanges();
		}

		public void UpdateRole(DTORole roleToUpdate, IList<DTOFaculty> chosenFaculties)
		{
			DACRole dacRole = new DACRole(_modelEntities);
			DACFaculty dacFaculty = new DACFaculty(_modelEntities);

			var foundRole = dacRole.GetRoleById(roleToUpdate.Id);
			if (foundRole == null)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.RoleDoesNotExistAnyMore, roleToUpdate.Id));
			}

			if (chosenFaculties.Count == 0)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.RoleMustHaveAtLeastOneFunctionality, roleToUpdate.Name));
			}

			foundRole.Name = roleToUpdate.Name;
			foundRole.Description = roleToUpdate.Description;
			foundRole.Faculties.Load();
			foundRole.Faculties.Clear();
			foreach (var faculty in chosenFaculties)
			{
				foundRole.Faculties.Add(dacFaculty.GetFacultyById(faculty.Id));
			}

			_modelEntities.SaveChanges();
		}

		//uzyj tego
		//usun powiazania z wybranymi funkcjonalnosciami (poki co, potem trzeba tez o
		//powiazaniach ze strukture node pamietac oraz z person
		public void DeleteRole(int roleId)
		{
			DACRole dacRole = new DACRole(_modelEntities);
			var foundRole = dacRole.GetRoleById(roleId);
			if (foundRole == null)
			{
				throw new InvalidOperationException(string.Format(ExceptionMessages.RoleDoesNotExistAnyMore, roleId));
			}

			_modelEntities.DeleteObject(foundRole);
			_modelEntities.SaveChanges();
		}
	}
}
